
package fr.mehfile.api.parser;

import fr.mehfile.view.utils.Utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;

public class XmlAgentParser {

    private static final String TAG = "XmlAgentParser";

    private SAXParser parser;
    private XmlAgentParserHandler xmlParser;

    public XmlAgentParser(Context context) throws Exception {

        xmlParser = new XmlAgentParserHandler(context);

        SAXParserFactory factory = SAXParserFactory.newInstance();
        parser = factory.newSAXParser();
    }

    public UpdateData parse(Context context, InputStream message) throws Exception {

        if (Utils.isDebugMode()) {
            if (message != null) {
                Writer writer = new StringWriter();

                char[] buffer = new char[1024];
                try {
                    Reader reader = new BufferedReader(
                            new InputStreamReader(message, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                } finally {
                    message.close();
                }
                Utils.debugger.logVerbose(TAG, "message : " + writer.toString());
                message = new ByteArrayInputStream(writer.toString().getBytes("UTF-8"));
            }
        }

        parser.parse(message, xmlParser);

        return xmlParser.getUpdateData();

    }
}
